package com.dunqi.gpm.shunqing.home.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatSpinner;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.dunqi.gpm.shunqing.KongApp;
import com.dunqi.gpm.shunqing.R;
import com.dunqi.gpm.shunqing.common.api.ApiFactory;
import com.dunqi.gpm.shunqing.common.api.RxSchedulers;
import com.dunqi.gpm.shunqing.common.base.BaseAct;
import com.dunqi.gpm.shunqing.common.base.ComObserver;
import com.dunqi.gpm.shunqing.common.base.Data;
import com.dunqi.gpm.shunqing.common.util.Arith;
import com.dunqi.gpm.shunqing.common.util.CommonUtil;
import com.dunqi.gpm.shunqing.common.util.FormUtil;
import com.dunqi.gpm.shunqing.common.util.JsonUtils;
import com.dunqi.gpm.shunqing.common.util.LogUtils;
import com.dunqi.gpm.shunqing.common.util.RequestBodyUtil;
import com.dunqi.gpm.shunqing.common.util.TimeUtil;
import com.dunqi.gpm.shunqing.common.view.ComTitleBar;
import com.dunqi.gpm.shunqing.common.view.NoScrollGridView;
import com.dunqi.gpm.shunqing.home.adapter.PhotoAdapter;
import com.dunqi.gpm.shunqing.home.adapter.SpinnerAdapter;
import com.dunqi.gpm.shunqing.home.bean.BelongType;
import com.dunqi.gpm.shunqing.home.bean.Branch;
import com.dunqi.gpm.shunqing.home.bean.Page;
import com.dunqi.gpm.shunqing.home.bean.ProjectTimeline;
import com.dunqi.gpm.shunqing.home.constance.Constance;
import com.dunqi.gpm.shunqing.home.widget.DatePickerDiaglog;
import com.foamtrace.photopicker.PhotoPickerActivity;
import com.foamtrace.photopicker.PhotoPreviewActivity;
import com.foamtrace.photopicker.SelectModel;
import com.foamtrace.photopicker.intent.PhotoPickerIntent;
import com.foamtrace.photopicker.intent.PhotoPreviewIntent;
import com.nanchen.compresshelper.CompressHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.vov.vitamio.utils.Log;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class UpdateProgressActivity extends BaseAct implements AdapterView.OnItemClickListener, TextWatcher {
    @BindView(R.id.title_bar)
    ComTitleBar titleBar;
    @BindView(R.id.spinner1)
    AppCompatSpinner spinner1;
    @BindView(R.id.spinner2)
    AppCompatSpinner spinner2;
    @BindView(R.id.yes_rb)
    RadioButton yesRb;
    @BindView(R.id.no_rb)
    RadioButton noRb;
    @BindView(R.id.plan_add_money)
    TextView planAddMoney;
    @BindView(R.id.complete_money)
    EditText completeMoney;
    @BindView(R.id.percent_money)
    TextView percentMoney;
    @BindView(R.id.year_percent_money)
    TextView yearPercentMoney;
    @BindView(R.id.actual_start_time_view)
    TextView actualStartTimeView;
    @BindView(R.id.actual_end_time)
    TextView actualEndTime;
    @BindView(R.id.progress_content_edit)
    EditText progressContentEdit;
    @BindView(R.id.next_work_plan)
    EditText nextWorkPlan;
    @BindView(R.id.next_plan_money)
    EditText nextPlanMoney;
    @BindView(R.id.grid_view)
    NoScrollGridView gridView;
    @BindView(R.id.remark_tv)
    EditText remarkTv;
    @BindView(R.id.time)
    TextView reportTime;
    @BindView(R.id.want_get_money)
    EditText wantGetMoney;
    @BindView(R.id.actual_end_time_container)
    View actual_end_time_container;
    @BindView(R.id.want_get_money_container)
    View want_get_money_container;

    String actualStartTimeString = "";
    String actualEndTimeString = "";
    @BindView(R.id.has_problem_cb)
    CheckBox hasProblemCb;
    @BindView(R.id.spinner_problem_type)
    AppCompatSpinner spinnerProblemType;
    @BindView(R.id.problem_des_edit)
    EditText problemDesEdit;
    @BindView(R.id.attach_branch_tv)
    TextView attachBranchTv;
    @BindView(R.id.suggest_edit)
    EditText suggestEdit;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.plan_add_money_label)
    TextView planAddMoneyLabel;
    @BindView(R.id.complete_money_label)
    TextView completeMoneyLabel;
    @BindView(R.id.percent_money_label)
    TextView percentMoneyLabel;
    @BindView(R.id.cb_accessory)
    CheckBox cb_accessory;

    private int type;
    List<String> data = new ArrayList<>();
    ArrayList<Branch> branchess;
    private PhotoAdapter adapter;

    ArrayList<ProjectTimeline> dataMain = new ArrayList<>();
    private long projectId;
    private String time;
    private long proAnnualPlanId;
    private long proPlanProgressId;
    private ArrayList<BelongType> typess;
    private int planYear;

    @Override
    protected void refreshData(Bundle savedInstanceState) {
        net();
    }

    private void net() {
        ApiFactory.getInstance()
                .queryProjectProgressList(projectId, null)
                .compose(RxSchedulers.<Page<ProjectTimeline>>io_main())
                .subscribe(new Consumer<Page<ProjectTimeline>>() {
                    @Override
                    public void accept(Page<ProjectTimeline> projectTimelinePage) throws Exception {
                        refreshUi(projectTimelinePage);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });

        ApiFactory.getInstance()
                .getAvailableList(null)
                .compose(RxSchedulers.<Data<ArrayList<Branch>>>io_main())
                .subscribe(new ComObserver<ArrayList<Branch>>() {
                    @Override
                    public void onSuccess(ArrayList<Branch> branches) {
                        branchess = branches;
                    }

                    @Override
                    public void onFinal() {

                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }
                });

        ApiFactory.getInstance()
                .getListByGroup("problem_type")
                .compose(RxSchedulers.<Data<ArrayList<BelongType>>>io_main())
                .subscribe(new ComObserver<ArrayList<BelongType>>() {
                    @Override
                    public void onSuccess(ArrayList<BelongType> types) {
                        typess = types;
                        if (types == null || types.isEmpty()) {
                            return;
                        }
                        String[] strings = new String[types.size() + 1];
                        strings[0] = "请选择";
                        for (int i = 1; i < strings.length; i++) {
                            strings[i] = types.get(i - 1).getCategoryName();
                        }
                        spinnerProblemType.setAdapter(new SpinnerAdapter(getActivity(), strings));
                    }

                    @Override
                    public void onFinal() {

                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposables(d);
                    }
                });
    }

    private void refreshUi(Page<ProjectTimeline> projectTimelinePage) {
        ArrayList<ProjectTimeline> list = projectTimelinePage.getList();
        dataMain.clear();

        if (list == null) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            ProjectTimeline projectTimeline = list.get(i);
            String reportPeriod = projectTimeline.getReportPeriod();
            if (TextUtils.isEmpty(reportPeriod)) {
                list.remove(i);
                i--;
            }
        }
        dataMain.addAll(list);

        String[] strings = new String[dataMain.size()];
        for (int i = 0; i < dataMain.size(); i++) {
            ProjectTimeline projectTimeline = dataMain.get(i);
            String reportPeriod = projectTimeline.getReportPeriod();
            String[] split = reportPeriod.split("-");
            strings[i] = split[0] + "年" + split[1] + "月汇报";
        }
        spinner1.setAdapter(new SpinnerAdapter(getActivity(), strings));

        commontRefresh();

    }

    private void commontRefresh() {
        if (dataMain.isEmpty()) {
            return;
        }
        int selectedItemPosition = spinner1.getSelectedItemPosition();
        ProjectTimeline item = dataMain.get(selectedItemPosition);

        double currentPeriodInvestiment = item.getCurrentPeriodInvestiment();
        planAddMoney.setText(currentPeriodInvestiment + "");

        String trim = completeMoney.getText().toString().trim();
        if (TextUtils.isEmpty(trim)) {
            trim = "0";
        }
        double v = Double.parseDouble(trim);
        if (currentPeriodInvestiment != 0) {
            double div = Arith.div(v * 100, currentPeriodInvestiment, 2);
            percentMoney.setText(div + "%");
        }
        yearPercentMoney.setText(item.getPercentEndCurrOfYear() + "");
    }

    @Override
    protected void initUiAndListener() {
        Intent intent = getIntent();
        type = intent.getIntExtra(Constance.TYPE, 0);
        projectId = intent.getLongExtra(Constance.PROJECTID, 0);
        //        auditStete = intent.getIntExtra(Constance.AUDITSTATE, -2);
        proAnnualPlanId = intent.getLongExtra(Constance.PROANNUALPLANID, -2);
        proPlanProgressId = intent.getLongExtra(Constance.PROPLANPROGRESSID, -2);
        planYear = intent.getIntExtra(Constance.PLAN_YEAR, 0);

        time = intent.getStringExtra(Constance.TIME);

        if (type == 0) {
            planAddMoneyLabel.setText("本月计划投资(万元):");
            completeMoneyLabel.setText("本月完成投资(万元):");
            percentMoneyLabel.setText("本月投资占年度投\\n资百分比:");
        }
        if (TextUtils.isEmpty(time)) {
            reportTime.setVisibility(View.GONE);
            spinner1.setVisibility(View.VISIBLE);
        } else {
            reportTime.setText(TimeUtil.getTen(time));
            reportTime.setVisibility(View.VISIBLE);
            spinner1.setVisibility(View.GONE);
        }

        data.add(null);
        adapter = new PhotoAdapter(getActivity(), data);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);

        String[] strings = {"进展顺利", "基本正常", "进度滞后", "申请结项"};
        spinner2.setAdapter(new SpinnerAdapter(getActivity(), strings));

        if (type == 1) {
            yesRb.performClick();
            spinner2.setSelection(3);
        } else {
            noRb.performClick();
            want_get_money_container.setVisibility(View.GONE);
        }

        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                commontRefresh();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 3) {
                    actual_end_time_container.setVisibility(View.VISIBLE);
                } else {
                    actual_end_time_container.setVisibility(View.GONE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        completeMoney.addTextChangedListener(this);
        titleBar.setOnClickListenerOfRight(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                commit();
            }
        });
        yesRb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    want_get_money_container.setVisibility(View.VISIBLE);
                } else {
                    want_get_money_container.setVisibility(View.GONE);
                }
            }
        });

        hasProblemCb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                container.setVisibility(isChecked ? View.VISIBLE : View.GONE);
            }
        });

        attachBranchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAttachBranch();
            }
        });

        cb_accessory.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                gridView.setVisibility(b ? View.VISIBLE : View.GONE);
            }
        });
    }

    boolean[] checheds;

    private void showAttachBranch() {
        if (branchess == null) {
            return;
        }
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("问题涉及部门(可多选)");
        final String[] items = new String[branchess.size()];
        if (checheds == null) {
            checheds = new boolean[branchess.size()];
        }
        for (int i = 0; i < branchess.size(); i++) {
            items[i] = branchess.get(i).getOrgShortName();
        }

        final boolean[] booleans = checheds.clone();

        builder.setMultiChoiceItems(items, booleans, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // 关闭提示框
                checheds = booleans.clone();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < booleans.length; i++) {
                    if (booleans[i]) {
                        sb.append(" ");
                        sb.append(items[i]);
                        sb.append(" ");
                        sb.append(",");
                    }
                }
                if (!TextUtils.isEmpty(sb)) {
                    sb.delete(sb.length() - 1, sb.length());
                }
                attachBranchTv.setText(sb);
                arg0.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // 关闭提示框
                arg0.dismiss();
            }
        });
        builder.show();
    }

    //提交
    private void commit() {
        if (dataMain.isEmpty()) {
            return;
        }
        final HashMap<String, String> param = new HashMap<>();

        param.put("projectId", String.valueOf(projectId));
        String completeMoneys = completeMoney.getText().toString().trim();
//        if (TextUtils.isEmpty(completeMoneys)) {
//            CommonUtil.showSingleToast("请填写本期完成投资");
//            return;
//        }
        try {
            Float.parseFloat(completeMoneys);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            CommonUtil.showSingleToast("请准确填写本期完成投资金额");
            return;
        }
        int selectedItemPosition = spinner2.getSelectedItemPosition();
        if (selectedItemPosition == 3) {
            if (TextUtils.isEmpty(actualEndTimeString)) {
                CommonUtil.showSingleToast("请选择竣工时间");
                return;
            }
            param.put("actualCompleteTime", actualEndTimeString);
        }
//        if (TextUtils.isEmpty(actualStartTimeString)) {
//            CommonUtil.showSingleToast("请选择开工时间");
//            return;
//        }
        param.put("actualStartTime", actualStartTimeString);

        String progressContent = progressContentEdit.getText().toString().trim();
        if (TextUtils.isEmpty(progressContent)) {
            CommonUtil.showSingleToast("请填写进展情况");
            return;
        }
        param.put("progressDesc", progressContent);
        if (yesRb.isChecked()) {
            String wantGetMoneyNum = wantGetMoney.getText().toString().trim();
            if (TextUtils.isEmpty(wantGetMoneyNum)) {
                wantGetMoneyNum = "0";
            }
            try {
                Float.parseFloat(wantGetMoneyNum);
            } catch (NumberFormatException e) {
                e.printStackTrace();
                CommonUtil.showSingleToast("请填写正确的结项金额");
                return;
            }
            param.put("settleAmount", wantGetMoneyNum);
        }
        String nextPeriodPlanDesc = this.nextWorkPlan.getText().toString().trim();
//        if (TextUtils.isEmpty(nextPeriodPlanDesc)) {
//            CommonUtil.showSingleToast("请填写下期工作计划");
//            return;
//        }
        param.put("nextPeriodPlanDesc", nextPeriodPlanDesc);

        String nextPeriodPlanFund = nextPlanMoney.getText().toString().trim();
//        if (TextUtils.isEmpty(nextPeriodPlanFund)) {
//            CommonUtil.showSingleToast("请填写下期计划投资");
//            return;
//        }
        param.put("nextPeriodPlanFund", nextPeriodPlanFund);

        String remark = remarkTv.getText().toString().trim();

        ProjectTimeline item = dataMain.get(spinner1.getSelectedItemPosition());

        if (!TextUtils.isEmpty(time)) {
            param.put("reportPeriod", time);
        }
        if (proAnnualPlanId != 0) {
            param.put("proAnnualPlanId", String.valueOf(proAnnualPlanId));
        }
        int position = spinner2.getSelectedItemPosition() + 1;
        if (proPlanProgressId == 0) {
            proPlanProgressId = item.getProPlanProgressId();
        }
        param.put("proPlanProgressId", String.valueOf(proPlanProgressId));
        if (planYear != 0) {
            param.put("planYear", String.valueOf(planYear));
        }
        param.put("progressType", String.valueOf(position));
        param.put("applySettlement", yesRb.isChecked() ? "1" : "0");
        param.put("currentPeriodInvested", completeMoneys);
        param.put("remark", remark);
        HashMap<String, RequestBody> bodyMap = new HashMap<>();
        param.put("saveType", "submit");
        if (hasProblemCb.isChecked()) {
            if (checheds == null) {
                t("请添加涉及部门");
                return;
            }
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < checheds.length; i++) {
                if (checheds[i]) {
                    int orgId = branchess.get(i).getOrgId();
                    sb.append(orgId);
                    sb.append(",");
                }
            }
            if (!TextUtils.isEmpty(sb)) {
                sb.delete(sb.length() - 1, sb.length());
            }
            param.put("involveDepartment", sb.toString());
            int itemPosition = spinnerProblemType.getSelectedItemPosition();
            if (itemPosition == 0) {
                t("请选择问题类型");
                return;
            }
            String categoryCode = typess.get(itemPosition - 1).getCategoryCode();
            param.put("problemType", categoryCode);

            String problemDesc = getProblemDesc();
            if (!TextUtils.isEmpty(problemDesc)) {
                param.put("problemDesc", problemDesc);
            }
            String measuresSuggestion = getMeasuresSuggestion();
            if (!TextUtils.isEmpty(measuresSuggestion)) {
                param.put("measuresSuggestion", measuresSuggestion);
            }
            param.put("hasProblem", "1");
        }
        FormUtil.AddHeader(param);
        //        MultipartBody.Builder builder = new MultipartBody.Builder();
        if (cb_accessory.isChecked()) {
            ArrayList<String> photos = new ArrayList<>();
            ArrayList<String> photosTemp = getPhotos();
            if (photosTemp.size() >0) {
                //处理压缩图片
                for (String photoPath : photosTemp) {
                    photos.add(photoPath);
//                    File newFile =new File(photoPath);
//                    LogUtils.w("photo",photoPath+"      --> "+newFile.length());
                }
                String[] uploadFileRemark = new String[photos.size()];
                for (int i = 0; i < photos.size(); i++) {
                    uploadFileRemark[i] = "上传文件备注" + (i + 1);
                }
                param.put("uploadFileRemark", JsonUtils.toJson(uploadFileRemark));
                for (String photo : photos) {
                    File newFile = CompressHelper.getDefault(KongApp.getContext()).compressToFile(new File(photo));
//                LogUtils.w("photo",newFile.getAbsolutePath()+"      --> "+newFile.length());
                    bodyMap.put("uploadFile\"; filename=\"" + newFile.getName(), RequestBodyUtil.get(newFile));
                    //builder.addFormDataPart("uploadFile", newFile.getName(), RequestBodyUtil.get(newFile));
                    //fileName不能为null，会报错
                }
            }
        }
        for (Map.Entry<String, String> entry : param.entrySet()) {
            bodyMap.put(entry.getKey(), RequestBody.create(MediaType.parse("multipart/form-data"), entry.getValue()));
            //            builder.addFormDataPart(entry.getKey(), entry.getValue()); // 这种添加不是multipart/form-data类型，所以会报错
        }
        //final ProgressDialog dialog = ProgressDialog.show(this, "提示", "正在提交");
//        ApiFactory.getInstance()
//                .updateProgress(bodyMap)
//                .compose(RxSchedulers.<Data>io_main())
//                .subscribe(new Consumer<Data>() {
//                    @Override
//                    public void accept(Data data) throws Exception {
//                        dialog.dismiss();
//                        setResult(RESULT_CODE);
//                        CommonUtil.showSingleToast("填写申请成功");
//                        finish();
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) {
//                        dialog.dismiss();
//                        CommonUtil.showSingleToast("填写申请失败");
//                    }
//                });
    }

    public static final int RESULT_CODE = 653;

    public String getMeasuresSuggestion() {
        return suggestEdit.getText().toString().trim();
    }

    public String getProblemDesc() {
        return problemDesEdit.getText().toString().trim();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_create_progress;
    }

    @OnClick({R.id.actual_start_time_view, R.id.actual_end_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.actual_start_time_view:
                final DatePickerDiaglog diaglog = new DatePickerDiaglog(getActivity());
                diaglog.show();
                diaglog.setCanceledOnTouchOutside(true);
                diaglog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        String time = diaglog.getTime();
                        actualStartTimeView.setText(time);
                        actualStartTimeString = time + " 00:00:00";
                    }
                });
                break;
            case R.id.actual_end_time:
                final DatePickerDiaglog diaglog1 = new DatePickerDiaglog(getActivity());
                diaglog1.show();
                diaglog1.setCanceledOnTouchOutside(true);
                diaglog1.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        String time = diaglog1.getTime();
                        actualEndTime.setText(time);
                        actualEndTimeString = time + " 00:00:00";
                    }
                });
                break;
        }
    }

    /**
     * homeMenuId
     *
     * @param context
     * @param projectId
     * @param type      0 /填写新的进展汇报  1申请结项
     */
    public static void start(Context context, long projectId, int type) {
        Intent intent = new Intent(context, UpdateProgressActivity.class);
        intent.putExtra(Constance.TYPE, type);
        intent.putExtra(Constance.PROJECTID, projectId);
        context.startActivity(intent);
    }

    /**
     * @param context
     * @param projectId
     * @param type
     * @param auditState
     * @param time       汇报期
     */
    public static void start(Activity context, long projectId, int type
            , int auditState, String time, long proAnnualPlanId, long proPlanProgressId, int planYear) {
        Intent intent = new Intent(context, UpdateProgressActivity.class);
        intent.putExtra(Constance.TYPE, type);
        intent.putExtra(Constance.PROJECTID, projectId);
        intent.putExtra(Constance.AUDITSTATE, auditState);
        intent.putExtra(Constance.TIME, time);
        intent.putExtra(Constance.PROANNUALPLANID, proAnnualPlanId);
        intent.putExtra(Constance.PROPLANPROGRESSID, proPlanProgressId);
        intent.putExtra(Constance.PLAN_YEAR, planYear);
        context.startActivityForResult(intent, 548);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String path = data.get(position);

        if (TextUtils.isEmpty(path)) {
            //
            PhotoPickerIntent intent = new PhotoPickerIntent(getActivity());
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照， 默认false
            intent.setMaxTotal(Constance.MAX_PIC); // 最多选择照片数量，默认为9
            ArrayList<String> paths = getPhotos();
            intent.setSelectedPaths(paths); // 已选中的照片地址， 用于回显选中状态
            // intent.setImageConfig(config);
            startActivityForResult(intent, Constance.REQUEST_CAMERA_CODE);
        } else {
            PhotoPreviewIntent intent = new PhotoPreviewIntent(getActivity());
            intent.setCurrentItem(position - 1); // 当前选中照片的下标
            ArrayList<String> paths = getPhotos();
            intent.setPhotoPaths(paths); // 已选中的照片地址
            startActivityForResult(intent, Constance.REQUEST_PREVIEW_CODE);
        }
    }

    @NonNull
    public ArrayList<String> getPhotos() {
        ArrayList<String> paths = new ArrayList<>();
        paths.addAll(data);
        paths.remove(0);
        return paths;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                // 选择照片
                case Constance.REQUEST_CAMERA_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                //                // 拍照
                //                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                //                    if(captureManager.getCurrentPhotoPath() != null) {
                //                        captureManager.galleryAddPic();
                //                        // 照片地址
                //                        String imagePaht = captureManager.getCurrentPhotoPath();
                //                        // ...
                //                    }
                //                    break;
                // 预览
                case Constance.REQUEST_PREVIEW_CODE:
                    refreshAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
                //            }
            }
        }
    }

    private void refreshAdpater(ArrayList<String> paths) {
        // 处理返回照片地址
        data.clear();
        data.add(null);
        data.addAll(paths);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //        String trim = completeMoney.getText().toString().trim();
        //        double v = Double.parseDouble(trim);
        commontRefresh();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
